package org.frankkie.parcdroid;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import java.io.PrintStream;
import java.util.List;

/**
 * ParcDroid, MainActivity.
 * Start de App, init alles.
 * @author frankkie
 * @see MapActivity
 */
public class MainActivity extends MapActivity {

  MapView mapView;
  public static boolean route_displayed = false;
  public static LocationManager locationManager;
  public static Location location;
  public static MapController mapController;
  List<Overlay> mapOverlays;
  Drawable drawable;
  OverlayDing itemizedOverlay;
  LocationListener deListener;
  OverlayDing mijnLokatieOverlay;
  public static Context deContext;
  public static boolean fakeLokatieGebruiken = false;
  /**
   * Als je GPS-Positie veranderd, 
   * moet de kaart daar dan wel of niet naar toe scrollen.
   */
  public static boolean animateToMijnLokatieZodraLokatieIsVeranderd = false;

  /**
   * Ga naar...
   * Voert de actie uit die hoort bij
   * de menu-optie 'Ga Naar...'.
   * Het opent een submenu met de opties:
   * "GPS-Positie" en "Efteling".
   * De Map wordt verschoven tot dit punt
   * het midden van de kaart staat.
   */
  public void menuOptie1() {
    ////////
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast_layout,
            (ViewGroup) findViewById(R.id.toast_layout_root));

    ImageView image = (ImageView) layout.findViewById(R.id.image);
    image.setImageResource(R.drawable.androidmarker);
    TextView text = (TextView) layout.findViewById(R.id.text);
    text.setText("Hello! This is a custom toast!");

    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
    ///////
  }

  /**
   * Sluit het programma.
   * Voert de actie uit die hoort bij
   * "Finish" uit het Menu.
   */
  public void menuOptie2() {
    System.out.println();
    this.finish();
    System.exit(0);
  }

  /**
   * Zoekt de juiste actie bij een menu-optie
   * @param item
   * @return boolean of de menu-optie is gebruikt.
   */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("Option: " + item.getItemId());
    switch (item.getItemId()) {
      case 1: {
        menuOptie1();
        return true;
      }

      case 2: {
        menuOptie2();
        return true;
      }

      case 3: {
        mapController.animateTo(OverlayDing.getPoint(location.getLatitude(), location.getLongitude()));
        return true;
      }

      case 4: {
        mapController.animateTo(OverlayDing.getPoint(51.651123, 5.048898));
        return true;
      }
      case 5: {
        toggleDeFakeLokatie();
        return true;
      }
      case 6: {
        fakeLokatieInvullen();
        return false;
      }
    }
    return super.onOptionsItemSelected(item);
  }

  public void toggleDeFakeLokatie() {
    //TOGGLE
    //fakeLokatieGebruiken = !fakeLokatieGebruiken;
    if (fakeLokatieGebruiken){
      fakeLokatieGebruiken=false;
    } else {
      fakeLokatieGebruiken=true;
    }
    //TOGGLE
    if (fakeLokatieGebruiken) {
      locationManager.removeUpdates(deListener);
      Toast.makeText(getApplicationContext(), "Fake Lokatie staat nu AAN", Toast.LENGTH_SHORT).show();
    } else {
      locationManager.removeUpdates(deListener);
      long minTime = 1;
      float minDistance = 1;
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, deListener);
      Toast.makeText(getApplicationContext(), "Fake Lokatie staat nu UIT", Toast.LENGTH_LONG).show();
    }
    //Proberen om meteen te repainten
      mapController.scrollBy(1, 1);
      mapController.scrollBy(-1, -1);
  }

  public void fakeLokatieInvullen() {
    ///dr moet een pop-up venstertje komen waar je je lokatie op kan invullen.

  }


  /**
   * Maakt het menu.
   * Wordt getoont als er op de
   * (Hardware)Menu-knop wordt gedrukt.
   * @param menu
   * @return boolean result = super.onCreateOptionsMenu(menu);
   */
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    boolean result = super.onCreateOptionsMenu(menu);
    menu.add(0, 1, 0, R.string.menu_optie1);
    menu.add(0, 2, 0, R.string.menu_optie2);
    SubMenu menuGaNaar = menu.addSubMenu("Ga naar...");
    menuGaNaar.add(0, 3, 0, "GPS Positie");
    menuGaNaar.add(0, 4, 0, "Efteling");
    SubMenu menuFakeLokatie = menu.addSubMenu("Fake Lokatie...");
    menuFakeLokatie.add(0, 5, 0, "Toggle");
    menuFakeLokatie.add(0, 6, 0, "Kies Locatie invoeren...");
    return result;
  }

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    //System.out en System.err doorlinken naar de DDMS (logcat)
    System.setErr(new PrintStream(new SystemOut("System.err")));
    System.setOut(new PrintStream(new SystemOut("System.out")));
    System.out.println("ParcDroid.MainActivity");

    //
    deContext = getApplicationContext();
    this.setContentView(R.layout.main);
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapController = mapView.getController();

    //Kaart centreren boven de efteling
    GeoPoint stoomCaroeselPoint = OverlayDing.getPoint(51.651123, 5.048898);
    mapController.setCenter(stoomCaroeselPoint);
    mapController.setZoom(16);
    mapView.setSatellite(true);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!locationManager.isProviderEnabled("gps")) {
      Toast.makeText(getApplicationContext(), "GPS staat niet aan !!!", Toast.LENGTH_LONG);
      this.finish();
    }

    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    ////OVERLAY START
    mapOverlays = mapView.getOverlays();
    drawable = this.getResources().getDrawable(R.drawable.demarker50);
    itemizedOverlay = new OverlayDing(drawable, this);
    ////EINDE OVERLAY START

    ///Zet Markers
    OverlayItem stoomCaroeselItem = new OverlayItem(stoomCaroeselPoint, "StoomCaroesel", "De StoomCaroesel staat hier");
    itemizedOverlay.addOverlay(stoomCaroeselItem);
    ///Einde ZetMarkers

    /////ZOOI OVERLAY
    GeoPoint point = new GeoPoint(19240000, -99120000); //mexico
    OverlayItem overlayitem = new OverlayItem(point, "Mexico", "Mexico !");
    itemizedOverlay.addOverlay(overlayitem);
    GeoPoint point2 = new GeoPoint(35410000, 139460000); //japan
    OverlayItem overlayitem2 = new OverlayItem(point2, "Japan", "Japan !");
    itemizedOverlay.addOverlay(overlayitem2);
    /////EINDE ZOOI OVERLAY

    ///OVERLAY EIND
    OverlayDinges overlaydinges = new OverlayDinges();
    mapOverlays.add(overlaydinges);
    mapOverlays.add(itemizedOverlay);
    ///EINDE OVERLAY EIND

    ///////////////
    Drawable androidDrawable = this.getResources().getDrawable(R.drawable.androidmarker);
    mijnLokatieOverlay = new OverlayDing(androidDrawable, this);
    deLokatieIsVeranderd(location);
    mapOverlays.add(mijnLokatieOverlay);
    ///
    mapOverlays.add(new OverlayDebugInfo());
    ///////////////

    ///
    deListener = new LocationListener() {

      public void onLocationChanged(Location arg0) {
        System.out.println("onLocationChanged");
        deLokatieIsVeranderd(arg0);
        //throw new UnsupportedOperationException("Not supported yet.");
      }

      public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        System.out.println("onStatusChanged");
        //throw new UnsupportedOperationException("Not supported yet.");
      }

      public void onProviderEnabled(String arg0) {
        System.out.println("onProviderEnabled");
        //throw new UnsupportedOperationException("Not supported yet.");
      }

      public void onProviderDisabled(String arg0) {
        System.out.println("onProviderDisabled");
        //throw new UnsupportedOperationException("Not supported yet.");
      }
    };
    long minTime = 1;
    float minDistance = 1;
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, deListener);
  }

  @Override
  protected boolean isRouteDisplayed() {
    //throw new UnsupportedOperationException("Not supported yet.");
    return route_displayed;
  }

  @Override
  protected void onPause() {
    super.onPause();
    //Als de app wordt ge-pauze-erd
    //dan zorgen we dat hij de GPS-positie minder vaak refresh-t.
    //om de batterij te sparen.
    locationManager.removeUpdates(deListener);
    long minTime = 30;
    float minDistance = 5;
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, deListener);
  }

  @Override
  protected void onResume() {
    super.onResume();
    //Als de app weer verder gaat
    //dan refreshen we de positie weer vaak.
    locationManager.removeUpdates(deListener);
    long minTime = 1;
    float minDistance = 1;
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, deListener);
  }

  public void maakTosti(OverlayItem ding) {
    Toast.makeText(getApplicationContext(), "" + ding.getTitle() + "\n" + ding.getSnippet(), Toast.LENGTH_LONG).show();
  }

  public void deLokatieIsVeranderd(Location lo) {
    location = lo;
    try {
      mijnLokatieOverlay.wisDeOverlays();
      //GeoPoint mijnPoint = OverlayDing.getPoint(lo.getLatitude(),lo.getLongitude());
      System.out.println("Lokatie: " + lo.getLatitude() + " " + lo.getLongitude());
      GeoPoint mijnPoint = new GeoPoint((int) (lo.getLatitude() * 1E6), (int) (lo.getLongitude() * 1E6));
      OverlayItem mijnLokatieItem = new OverlayItem(mijnPoint, "HIER", "Hier ben je !");
      mijnLokatieOverlay.addOverlay(mijnLokatieItem);
      //Proberen om meteen te repainten
      mapController.scrollBy(1, 1);
      mapController.scrollBy(-1, -1);
      if (animateToMijnLokatieZodraLokatieIsVeranderd) {
        mapController.animateTo(mijnPoint);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
